let app = getApp()
let isLogin = false; //为了避免重复登录  这里是保存是否正在登录的状态
function postdata(url, data, success, page, fail) {
    const res = my.getStorageSync({key: 'token'});
    if (res) {
        data.token = res.data
        if (data.token === undefined) {
            wxlogin(page, () => {
                postdata(url, data, success, page, fail);
            })
        } else if (data.token === null) {
            wxlogin(page, () => {
                postdata(url, data, success, page, fail);
            })
        } else {
            wxrequest(url, data, success, page, "POST", fail)
        }
    } else {
        wxlogin(page, () => {
            postdata(url, data, success, page, fail);
        })
    }
}

function getdata(url, data, success, page, fail) {
    const res = my.getStorageSync({key: 'token'});
    if (res) {
        data.token = res.data
        if (data.token === undefined) {
            wxlogin(page, () => {
                getdata(url, data, success, page, fail);
            })
        } else if (data.token === null) {
            wxlogin(page, () => {
                getdata(url, data, success, page, fail);
            })
        } else {
            wxrequest(url, data, success, page, "GET", fail)
        }
    } else {
        wxlogin(page, () => {
            getdata(url, data, success, page, fail);
        })
    }
}

function wxrequest(url, data, success, page, method, fail) {
    if (!method) {
        method = "GET";
    }
    if (method !== "GET") {
        data = JSON.stringify(data)
    }
    my.httpRequest({
        url: app.globalData.baseurl + url,
        method: method,
        headers: {'Content-Type': 'application/json'},
        data: data,
        dataType: 'text',
        timeout: 10000,
        success: (res) => {
            const that = this;
            setTimeout(() => {
                my.hideLoading({
                    page: that,  // 防止执行时已经切换到其它页面，page指向不准确
                });
            }, 2000);
            let info = res.data;
            info = info.replace(/(^\s*)|(\s*$)/g, "");
            let resdata = JSON.parse(info);
            if (resdata.code == 200) {
                success(resdata.data);
            } else if (resdata.code == 401) {
                if (method === 'GET') {
                  wxlogin(page, () => {
                      getdata(url, data, success, page, fail);
                  });
                } else {
                  let _data = JSON.parse(data);
                  wxlogin(page, () => {
                      postdata(url, _data, success, page, fail);
                  });
                }
            } else if (resdata.code == 400) {
              my.showToast({
                content: resdata.data,
                type: "fail",
                duration: 3000
              })
            }else if (resdata.code == 500) {
                my.showToast({
                  content: '服务器异常,请重试',
                  type: "fail",
                  duration: 3000
                })
            } else {
                my.showToast({
                  content: resdata.msg,
                  type: "fail",
                  duration: 2000
                })
            }
        },
        fail: (res) => {
          console.log(res)
            const that = this;
            setTimeout(() => {
                my.hideLoading({
                    page: that,  // 防止执行时已经切换到其它页面，page指向不准确
                });
            }, 2000);
            let str = JSON.stringify(res);
            if (fail) {
                fail(res)
            } else if (res.error == 12) {
                my.showToast({
                    content: '网络错误,请检查网络',
                    type: "fail",
                    duration: 3000
                })
            } else if (res.error == 13) {
                my.showToast({
                    content: '请求超时，请重试',
                    type: "fail",
                    duration: 3000
                })
            } else {
                my.showToast({
                    content: '网络异常',
                    type: "fail",
                    duration: 3000
                })
            }
        }
    });
  // my.httpRequest({
  //   url: 'http://123.125.115.110/post',
  //   method: 'POST',
  //   data: {
  //     from: '支付宝',
  //     production: 'AlipayJSAPI',
  //   },
  //   dataType: 'json',
  //   success: function(res) {
  //     my.alert({ content: 'success' });
  //   },
  //   fail: function(res) {
  //     my.alert({ content: 'fail' });
  //   },
  //   complete: function(res) {
  //     my.hideLoading();
  //     my.alert({ content: 'complete' });
  //   }
  // });
}

function wxlogin(page, callback) {
    my.showLoading({
        content: '登录中',
        complete: () => {
            my.hideLoading();
        }
    })
    if (isLogin) {
        waitLogin(page, callback);
        return;
    } else {
        isLogin = true;
    }
    my.getAuthCode({
        scopes: 'auth_user',
        success: (res) => {
            my.hideLoading();
            my.getAuthUserInfo({
                success: (userInfo) => {
                    let info = {}
                    info['aliInfo'] = userInfo;
                    info.code = res.authCode;
                    info['source'] = 1;
                    my.httpRequest({
                        url: app.globalData.baseurl + '/Login/login',
                        headers: { 'content-type': 'application/json' },
                        method: 'POST',
                        dataType: 'text',
                        data: JSON.stringify(info),
                        success: (res) => {
                            var info = res.data;
                            info = info.replace(/(^\s*)|(\s*$)/g, "");
                            var resdata = JSON.parse(info);
                            if (resdata.code == '200') {
                              my.setStorageSync({
                                  key: "token",
                                  data: resdata.data
                              })
                              isLogin = false;
                              my.hideLoading()
                              // my.showToast({
                              //   content:"登录成功",
                              //   type:"success"
                              // })
                              if (callback) {
                                  callback();
                              } else {
                                  page.onLoad();
                              }
                            } else if (resdata.code == '500') {
                              my.showToast({
                                content: resdata.msg,
                                type: "fail",
                                duration: 1000
                              })
                            }else {
                              my.showToast({
                                content: resdata.data,
                                type: "fail",
                                duration: 1000
                              })
                            }
                        },
                    })
                },
                fail: (res) => {
                    my.showToast({
                        content: "登录失败",
                        type: "fail",
                        duration: 1000
                    })
                }
            });
        },
        fail: (res) => {
            my.showToast({
                content: "授权失败",
                type: "fail",
                duration: 500
            })
            // wx.showModal({
            //   title: '请授权',
            //   content: '未授权部分功能将无法使用',
            //   showCancel: false,
            //   success: function(res) {
            //     wx.openSetting({
            //       success:function(res){
            //         if (res.authSetting['scope.userInfo']) {
            //           wxlogin(page)
            //         }
            //         else{
            //           my.showToast({
            //             content:"授权失败",
            //             type:"fail"
            //           })
            //         }
            //       }
            //     })
            //   }
            // })
        }
    })
}
//等待登录中
function waitLogin(page, callback) {
  let interval = setInterval(() => {
    if (!isLogin) {
      clearInterval(interval)
      if (callback) {
        callback();
      } else {
        page.onLoad();
      }
    }
  }, 1000)
}
module.exports.postdata = postdata
exports.wxrequest = wxrequest
exports.getdata = getdata
exports.wxlogin = wxlogin